﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SIOsystem.Control;
using System.IO;

namespace SIOsystem
{
    public partial class ConfigForm : Form
    {
        public string uname = "";
        public long id = -1;
        public string rid = "";
        private string dbpath = "";
        public ConfigForm()
        {
            InitializeComponent();
        }

        private void ConfigForm_Load(object sender, EventArgs e)
        {
            DictionaryClass.fillSetMainClass(ref SetMainClass);
            DictionaryClass.fillSetMainClass(ref NewMainClass);
            DictionaryClass.fillProject(ref DeptList);
            DictionaryClass.fillOperator(ref OperatorList);
            DictionaryClass.fillRoles(ref RoleList);
            string connectionString = ConfigHelper.GetConnectionStringsConfig("SIOsystem.Properties.Settings.DatabaseConnectionString");
            int si=connectionString.IndexOf("ce=")+3;
            int ei=connectionString.IndexOf(";",si);
            if (ei>si)
            {
                dbpath=connectionString.Substring(si,ei-si);
            }
            if (File.Exists(dbpath))
            {
                DBPath.Text = dbpath;
            }
            else
            {
                DBPath.Text=dbpath = Application.StartupPath + @"\database\Database.mdb";
            }
            string dbbk = ConfigHelper.GetAppConfig("DBBackup");
            if (Directory.Exists(dbbk))
            {
                BKPath.Text = dbbk;
            }
        }

        private void SetMainClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (SetMainClass.Items.Count > 0)
            {
                long MID = 0;
                if (SetMainClass.SelectedValue != null)
                {
                    long.TryParse(SetMainClass.SelectedValue.ToString(), out MID);
                }
                if (MID == -1)
                {
                    DictionaryClass.fillProductClass(ref ProductList, MID);
                }else if (MID > 0)
                {
                    DictionaryClass.fillProductClass(ref ProductList, MID);
                    MainClassName.Text = SetMainClass.Text;
                }
                else
                {
                    ProductList.DataSource = null;
                    MainClassName.Text = "";
                }
            }
        }

        private void ProductList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ProductList.Items.Count > 0 && ((CheckedListBox)sender).DisplayMember!="")
            {
                long PID = 0;
                if (ProductList.SelectedValue != null)
                {
                    long.TryParse(ProductList.SelectedValue.ToString(), out PID);
                }
                ModProduct.Enabled = false;
                AddProduct.Enabled = false;
                if (PID > 0)
                {
                    DictionaryClass.fillModelClass(ref ModelList, PID);
                    NewProductName.Text = ProductList.Text;
                    NewProductName.Enabled = false;
                    ModelList.DropDownStyle = ComboBoxStyle.DropDownList;
                }
                else
                {
                    ModelList.DataSource = null;
                    NewProductName.Text = "";
                }
            }
        }

        private void ModelList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ModelList.Items.Count > 0)
            {
                long TID = 0;
                if (ModelList.SelectedValue != null)
                {
                    long.TryParse(ModelList.SelectedValue.ToString(), out TID);
                }
                if (TID > 0 && ModelList.DropDownStyle == ComboBoxStyle.DropDownList)
                {
                    string[] pInfo = OrderClass.getProductInfo(TID);
                    Price.Value = decimal.Parse(pInfo[1]);
                    Unit.Text = pInfo[2];
                    if (!AddProduct.Enabled)
                    {
                        ModProduct.Enabled = true;
                    }
                }
                else
                {
                    Price.Value = 0;
                    Unit.Text = "";
                    ModProduct.Enabled = false;
                }
            }
        }

        private void AddProduct_Click(object sender, EventArgs e)
        {
            if (NewProductName.Text == "")
            {
                MessageBox.Show("请填写商品名");
                return;
            }
            if (Price.Value == 0)
            {
                MessageBox.Show("请填写价格");
                return;
            }
            if (Unit.Text == "")
            {
                MessageBox.Show("请填写单位");
                return;
            }
            if (NewProductName.Enabled)
            {
                if (ProductList.FindString(NewProductName.Text) > -1)
                {
                    MessageBox.Show("该材料已存在");
                    return;
                }
                if (ModelList.FindString(ModelList.Text) > -1)
                {
                    MessageBox.Show("该规格已存在");
                    return;
                }
                if (ClassifyClass.insertClassify(toLong(SetMainClass.SelectedValue), NewProductName.Text, ModelList.Text
                    , double.Parse(Price.Value.ToString()), Unit.Text))
                {
                    MessageBox.Show("商品添加成功！");
                }
            } 
            else
            {
                if (ModelList.FindString(ModelList.Text) > -1)
                {
                    MessageBox.Show("该规格已存在");
                    return;
                }
                if (ClassifyClass.insertClassify(toLong(ProductList.SelectedValue), ModelList.Text
                    , double.Parse(Price.Value.ToString()), Unit.Text))
                {
                    MessageBox.Show("商品添加成功！");
                }
            }
            long MID = 0;
            if (SetMainClass.SelectedValue != null)
            {
                long.TryParse(SetMainClass.SelectedValue.ToString(), out MID);
            }
            if (MID > 0)
            {
                DictionaryClass.fillProductClass(ref ProductList, MID);
            }
        }

        private void ModProduct_Click(object sender, EventArgs e)
        {
            if (Price.Value == 0)
            {
                MessageBox.Show("请填写价格");
                return;
            }
            if (Unit.Text == "")
            {
                MessageBox.Show("请填写单位");
                return;
            }
            if (ModelList.Text == "")
            {
                MessageBox.Show("请填写规格");
                return;
            }
            if (ProductList.FindString(NewProductName.Text) > -1 
                && ProductList.FindString(NewProductName.Text)!=ProductList.SelectedIndex)
            {
                MessageBox.Show("该材料已存在");
                return;
            }
            if (ClassifyClass.updateClassify(toLong(ProductList.SelectedValue), NewProductName.Text, toLong(ModelList.SelectedValue), ModelList.Text
                , double.Parse(Price.Value.ToString()), Unit.Text))
            {
                ClassifyClass.updateProductName(toLong(ModelList.SelectedValue), NewProductName.Text +" " +ModelList.Text);
                MessageBox.Show("修改成功！");
            }
            long MID = 0;
            if (SetMainClass.SelectedValue != null)
            {
                long.TryParse(SetMainClass.SelectedValue.ToString(), out MID);
            }
            if (MID > 0)
            {
                DictionaryClass.fillProductClass(ref ProductList, MID);
            }
        }

        private void AddMainClass_Click(object sender, EventArgs e)
        {
            if (SetMainClass.FindString(MainClassName.Text) > -1)
            {
                MessageBox.Show("该分类已存在，不能添加");
            }
            else
            {
                if (ClassifyClass.insertClassify(MainClassName.Text))
                {
                    MessageBox.Show("添加成功！");
                    DictionaryClass.fillSetMainClass(ref SetMainClass);
                    DictionaryClass.fillSetMainClass(ref NewMainClass);
                } 
                else
                {
                    MessageBox.Show("添加失败！");
                }
            }
        }

        private void ModMainClass_Click(object sender, EventArgs e)
        {
            if (SetMainClass.FindString(MainClassName.Text) > 0)
            {
                MessageBox.Show("该分类已存在，不能修改");
            }
            else
            {
                if (ClassifyClass.updateClassify(toLong(SetMainClass.SelectedValue),MainClassName.Text))
                {
                    MessageBox.Show("修改成功！");
                    DictionaryClass.fillSetMainClass(ref SetMainClass);
                    DictionaryClass.fillSetMainClass(ref NewMainClass);
                }
                else
                {
                    MessageBox.Show("修改失败！");
                }
            }
        }

        private void DelMainClass_Click(object sender, EventArgs e)
        {
            if (ClassifyClass.deleteMainClass(toLong(SetMainClass.SelectedValue)))
            {
                MessageBox.Show("删除成功！");
                DictionaryClass.fillSetMainClass(ref SetMainClass);
                DictionaryClass.fillSetMainClass(ref NewMainClass);
            }
            else
            {
                MessageBox.Show("删除失败！");
            }
        }

        private void ChangeClass_Click(object sender, EventArgs e)
        {
            if (ProductList.CheckedItems.Count>0)
            {
                long[] CID = new long[ProductList.CheckedItems.Count];
                int i=0;
                foreach (DataRowView dr in ProductList.CheckedItems)
                {
                    CID[i++] = long.Parse(dr["CID"].ToString());
                }
                if (ClassifyClass.ChangeParentById(CID, toLong(NewMainClass.SelectedValue)))
                {
                    DictionaryClass.fillSetMainClass(ref SetMainClass);
                    DictionaryClass.fillSetMainClass(ref NewMainClass);
                    MessageBox.Show("迁移成功！");
                }
            }
        }

        private long toLong(object o)
        {
            return long.Parse(o.ToString());
        }

        private void initDB_Click(object sender, EventArgs e)
        {
            if (uname != "admin")
            {
                MessageBox.Show("只有管理员能初始化数据库");
                return;
            }
            ofd.InitialDirectory = @"c:\";
            ofd.RestoreDirectory = true;
            ofd.Filter = "初始库存数据|classify.csv";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                StreamReader sr = new StreamReader(ofd.FileName,Encoding.Default);
                string classify;
                classify = sr.ReadToEnd();
                string[] line = classify.Replace("\r\n","\r").Split('\r');
                sr.Close();
                ClassifyClass.initDB(line);
            }
        }

        private void DeptList_SelectedIndexChanged(object sender, EventArgs e)
        {
            ProjectName.Text = DeptList.Text;
            if (DeptList.Items.Count > 0)
            {
                long PID = 0;
                if (DeptList.SelectedValue != null)
                {
                    long.TryParse(DeptList.SelectedValue.ToString(), out PID);
                }
                if (PID > 0)
                {
                    string[] info = DictionaryClass.getProjectInfo(PID);
                    ProjectID.Text = info[0];
                    ProjectName.Text = info[1];
                    ProjectPlace.Text = info[2];
                    SendAddr.Text = info[3];
                    Connecter.Text = info[4];
                    Payer.Text = info[5];
                    if (info[6]=="进行中")
                    {
                        Status.SelectedIndex = 0;
                    } 
                    else
                    {
                        Status.SelectedIndex = 1;
                    }
                }
                AddDept.Enabled = false;
                ModDept.Enabled = true;
            }
        }

        private void AddDept_Click(object sender, EventArgs e)
        {
            if (DeptList.FindString(ProjectName.Text)>-1)
            {
                MessageBox.Show("项目已存在！");
                return;
            }
            if (ProjectName.Text.Length>0 
                && DeptClass.addProject(int.Parse(ProjectID.Text), ProjectName.Text,ProjectPlace.Text
                                        ,SendAddr.Text,Connecter.Text,Payer.Text,Status.SelectedItem.ToString()))
            {
                MessageBox.Show("添加成功！");
                DictionaryClass.fillProject(ref DeptList);
            }
        }

        private void ModDept_Click(object sender, EventArgs e)
        {
            if (DeptList.SelectedIndex != -1 && ProjectName.Text.Length > 0
                && DeptClass.modProject(ProjectName.Text, ProjectPlace.Text , SendAddr.Text, Connecter.Text
                                        , Payer.Text, Status.SelectedText, toLong(DeptList.SelectedValue)))
            {
                MessageBox.Show("修改成功！");
                DictionaryClass.fillProject(ref DeptList);
            }
        }

        private void BrowDBPath_Click(object sender, EventArgs e)
        {
            ofd.CheckFileExists = true;
            ofd.Filter = "数据库文件|database.mdb";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                DBPath.Text = ofd.FileName;
            }
        }

        private void SaveDBPath_Click(object sender, EventArgs e)
        {
            if (File.Exists(DBPath.Text))
            {
                ConfigHelper.UpdateConnectionStringsConfig("SIOsystem.Properties.Settings.DatabaseConnectionString"
                        , "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DBPath.Text + ";Jet OLEDB:Database Password=sywg1234;", false);
                MessageBox.Show("修改成功！重启后起效。");
            }
            else
            {
                MessageBox.Show("文件不存在！请重新选择。");
            }
        }

        private void BackupDB_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(BKPath.Text))
            {
                ConfigHelper.UpdateAppConfig("DBBackup", BKPath.Text);
                if (File.Exists(dbpath))
                {
                    try
                    {
                        File.Copy(dbpath, BKPath.Text + @"\" + DateTime.Now.ToString("yyyyMMddhhmmss.backup"), true);
                        MessageBox.Show("备份成功！");
                    }
                    catch { MessageBox.Show("备份出错！"); }
                }
                else
                {
                    MessageBox.Show("源数据库不存在！");
                }
            }
            else
            {
                MessageBox.Show("备份路径不存在！");
            }
        }

        private void BrowBKPath_Click(object sender, EventArgs e)
        {
            fbd.Description = "选择数据库备份路径（备份后格式为yyyyMMddhhmmss.backup）";
            fbd.SelectedPath = Application.StartupPath;
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                BKPath.Text = fbd.SelectedPath;
            }
        }

        private void RestoreDB_Click(object sender, EventArgs e)
        {
            ofd.CheckFileExists = true;
            ofd.RestoreDirectory = true;
            if (Directory.Exists(BKPath.Text))
            {
                ofd.InitialDirectory = BKPath.Text;
            }
            else
            {
                ofd.InitialDirectory = Application.StartupPath;
            }
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                if (MessageBox.Show("是否恢复选定数据库备份？建议恢复前先备份当前数据库。"
                    ,"恢复数据库备份",MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    try
                    {
                        File.Copy(ofd.FileName, dbpath, true);
                        MessageBox.Show("恢复成功！");
                    }
                    catch { MessageBox.Show("恢复出错！"); }
                }
            }
        }

        private void addNew_Click(object sender, EventArgs e)
        {
            AddDept.Enabled = true;
            ModDept.Enabled = false;
            ProjectID.Text = (OrderClass.getMaxAppSerials()+1).ToString();
            if (int.Parse(ProjectID.Text) < (DateTime.Now.Year - 2000) * 1000 + 1)
            {
                ProjectID.Text = (DateTime.Now.Year - 2000).ToString() + "001";
            }
            ProjectName.Text = "";
            ProjectPlace.Text = "";
            SendAddr.Text = "";
            Connecter.Text = "";
            //Payer.Text = "";
            Status.SelectedIndex=0;
        }

        private void OperatorList_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (OperatorList.SelectedRows.Count == 1)
            {
                AddOperator.Enabled = false;
                ModOperator.Enabled = true;
                NewName.Enabled = false;
                NewName.Text = OperatorList.Rows[e.RowIndex].Cells["登录名"].Value.ToString();
                switch (OperatorList.Rows[e.RowIndex].Cells["角色"].Value.ToString())
                {
                    case "系统管理员":
                        RoleList.SelectedIndex = 0;
                        break;
                    case "仓库管理员":
                        RoleList.SelectedIndex = 1;
                        break;
                    case "材料申购员":
                        RoleList.SelectedIndex = 2;
                        break;
                }
            }
        }

        private void newOp_Click(object sender, EventArgs e)
        {
            AddOperator.Enabled = true;
            ModOperator.Enabled = false;
            NewName.Enabled = true;
            NewName.Text = NewPassword.Text = Repwd.Text = "";
            RoleList.SelectedIndex = 0;
        }

        private void AddOperator_Click(object sender, EventArgs e)
        {
            if (uname != "admin")
            {
                MessageBox.Show("只有超级管理员能添加用户");
                return;
            }
            if (OperatorClass.addOperator(NewName.Text, NewPassword.Text, toLong(RoleList.SelectedValue)))
            {
                MessageBox.Show("操作员添加成功！");
                NewName.Text = NewPassword.Text = Repwd.Text = "";
                RoleList.SelectedValue = 0;
                DictionaryClass.fillOperator(ref OperatorList);
            }
        }

        private void ModOperator_Click(object sender, EventArgs e)
        {
            if (uname != "admin")
            {
                MessageBox.Show("只有超级管理员能修改用户");
                return;
            }
            long oid = long.Parse(OperatorList.SelectedRows[0].Cells["oid"].Value.ToString());
            if (OperatorClass.modRole(long.Parse(RoleList.SelectedValue.ToString()),oid))
            {
                if (NewPassword.Text.Trim().Length > 0 
                && NewPassword.Text == Repwd.Text )
                {
                    if (!OperatorClass.modPassword(NewPassword.Text, oid))
                    {
                        MessageBox.Show("密码修改失败！");
                        DictionaryClass.fillOperator(ref OperatorList);
                        return;
                    }
                }
                else if (NewPassword.Text != Repwd.Text)
                {
                    MessageBox.Show("两次密码不一致！");
                }
                MessageBox.Show("修改成功！");
                NewPassword.Text = Repwd.Text = "";
                DictionaryClass.fillOperator(ref OperatorList);
            }
            else
            {
                MessageBox.Show("角色修改失败！");
            }
        }

        private void NewProduct_Click(object sender, EventArgs e)
        {
            if (NewProductName.Text!="")
            {
                NewProductName.Text = "";
                NewProductName.Enabled = true;
                Price.Value = 0;
                Unit.Text = "";
                ModProduct.Enabled = false;
                ModelList.DataSource = null;
                ModelList.DropDownStyle = ComboBoxStyle.DropDown;
                ModProduct.Enabled = false;
                AddProduct.Enabled = true;
            }
        }

        private void NewModel_Click(object sender, EventArgs e)
        {
            if (NewProductName.Text != "")
            {
                Price.Value = 0;
                Unit.Text = "";
                ModProduct.Enabled = false;
                ModelList.DropDownStyle = ComboBoxStyle.DropDown;
                ModProduct.Enabled = false;
                AddProduct.Enabled = true;
            }
        }
    }
}
